package com.digitalchina.dcn.dcss.web.enums;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/7/14 0014.
 */
public class IDListTypeHandler extends BaseTypeHandler<List<Long>> {

    private Class<List<Long>> type;

    public IDListTypeHandler(Class<List<Long>> type) {
        if (type == null)
            throw new IllegalArgumentException("Type argument cannot be null");
        this.type = type;
    }

    private List<Long> convert(String value) {
        List<Long> idList = new ArrayList<Long>();
        if(!StringUtils.isEmpty(value)) {
            String[] idStrs = value.split(",");
            for(String resourceIdStr : idStrs) {
                if(StringUtils.isEmpty(resourceIdStr)) {
                    continue;
                }
                idList.add(Long.valueOf(resourceIdStr));
            }
        }
        return idList.size() > 0 ? idList : null;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<Long> longs, JdbcType jdbcType) throws SQLException {
        // baseTypeHandler已经帮我们做了parameter的null判断
        String ids;
        if(CollectionUtils.isEmpty(longs)) {
            ids = "";
        } else {
            StringBuilder s = new StringBuilder();
            for(Long id : longs) {
                s.append(id);
                s.append(",");
            }
            ids = s.toString();
        }
        preparedStatement.setString(i, ids);
    }

    @Override
    public List<Long> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return convert(resultSet.getString(s));
    }

    @Override
    public List<Long> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return convert(resultSet.getString(i));
    }

    @Override
    public List<Long> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return convert(callableStatement.getString(i));    }
}
